package zdyu.users.database;

import java.sql.*;
import java.util.Optional;

public class JDBCWrapper implements AutoCloseable {

    public JDBCWrapper(
            String databaseType,
            String host,
            Short port,
            String databaseName,
            String user,
            String passphrase
    ) {
        try {
            connectionOptional = Optional.ofNullable(
                    DriverManager.getConnection(
                            "jdbc:"
                                    + databaseType + "://"
                                    + host
                                    + ":" + port.toString()
                                    + "/" + databaseName,
                            user,
                            passphrase
                    )
            );
        } catch (SQLException e) {
            connectionOptional = Optional.empty();
        }
    }

    public Optional<PreparedStatement> getPreparedStatement(String sql, Object... values) {
        if (!(connectionOptional.isPresent())) return Optional.empty();

        PreparedStatement preparedStatement;
        try {
            preparedStatement = connectionOptional.get().prepareStatement(sql);
            for (int i = 0; i < values.length; i++) {
                preparedStatement.setObject(i + 1, values[i]);
            }
            return Optional.ofNullable(preparedStatement);
        } catch (SQLException e) {
            return Optional.empty();
        }
    }

    Optional<Connection> connectionOptional;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException ignored) {}
    }

    @Override
    public void close() throws Exception {
        if(connectionOptional.isPresent()) connectionOptional.get().close();
    }

}

